﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text.RegularExpressions;
using System.Text;
using Newtonsoft.Json;

namespace NetCoreClass
{
    public static class DataJson
    {

        /// <summary>
        /// 清除换行符\r \n "换成单引号"        
        /// </summary>
        public static string clear(this String str)
        {
            str = str.Replace((char)13, (char)0);
            str = str.Replace((char)10, (char)0);
            str = str.Replace((char)34, (char)39);
            return str;
        }
        /// <summary>
        /// 将JSON解析成DataSet只限标准的JSON数据
        /// 例如：Json＝{t1:[{name:'数据name',type:'数据type'}]} 或 Json＝{t1:[{name:'数据name',type:'数据type'}],t2:[{id:'数据id',gx:'数据gx',val:'数据val'}]}
        /// </summary>
        /// <param name="Json">Json字符串</param>
        /// <returns>DataSet</returns>
        public static DataSet ToDataSet(this String Json)
        {
            try
            {
                DataSet ds = new DataSet();
             
                object obj = JsonConvert.DeserializeObject(Json);
                Dictionary<string, object> datajson = (Dictionary<string, object>)obj;


                foreach (var item in datajson)
                {
                    DataTable dt = new DataTable(item.Key);
                    object[] rows = (object[])item.Value;
                    foreach (var row in rows)
                    {
                        Dictionary<string, object> val = (Dictionary<string, object>)row;
                        DataRow dr = dt.NewRow();
                        foreach (KeyValuePair<string, object> sss in val)
                        {
                            if (!dt.Columns.Contains(sss.Key))
                            {
                                dt.Columns.Add(sss.Key.ToString());
                                dr[sss.Key] = sss.Value;
                            }
                            else
                                dr[sss.Key] = sss.Value;
                        }
                        dt.Rows.Add(dr);
                    }
                    ds.Tables.Add(dt);
                }
                return ds;
            }
            catch
            {
                return null;
            }
        }

        public static DataTable ToDataTable(this string strJson)
        {
            //转换json格式
            //  strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            try
            {
                strJson = strJson.Substring(strJson.IndexOf("[") + 1);
                strJson = strJson.Substring(0, strJson.IndexOf("]"));

                //获取数据   
                rg = new Regex(@"(?<={)[^}]+(?=})");
                MatchCollection mc = rg.Matches(strJson);
                for (int i = 0; i < mc.Count; i++)
                {
                    string strRow = mc[i].Value;
                    string[] strRows = strRow.Split(',');

                    //创建表   
                    if (tb == null)
                    {
                        tb = new DataTable();
                        tb.TableName = strName;
                        foreach (string str in strRows)
                        {
                            var dc = new DataColumn();
                            string[] strCell = str.Split(':');

                            if (strCell[0].Substring(0, 1) == "\"")
                            {
                                int a = strCell[0].Length;
                                dc.ColumnName = strCell[0].Substring(1, a - 2);
                            }
                            else
                            {
                                dc.ColumnName = strCell[0].ToString().Replace("\"", "").Trim();
                            }
                            dc.DataType = typeof(string);
                            // dc.MaxLength = 200;
                            tb.Columns.Add(dc);

                        }
                        tb.AcceptChanges();
                    }

                    //增加内容   
                    DataRow dr = tb.NewRow();
                    for (int r = 0; r < strRows.Length; r++)
                    {
                        try
                        {

                            string[] a = strRows[r].Split(':');
                            string col = a[0].ToString().Replace("\"", "").Trim();
                            dr[col] = a[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");

                        }
                        catch (Exception e)
                        {

                            throw e;
                        }
                    }
                    tb.Rows.Add(dr);
                    tb.AcceptChanges();
                }

            }
            catch (Exception exp)
            {

            }

            return tb;

        }
        /// <summary>
        /// 将DataSet转化成JSON数据
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string ToJson(this DataSet ds)
        {
            string json = string.Empty;
            try
            {
                if (ds.Tables.Count == 0)
                    throw new Exception("DataSet中Tables为0");
                json = "{";
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    json += "'T" + (i + 1) + "':[";
                    for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                    {
                        json += "{";
                        for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
                        {
                            //json +="'"+ ds.Tables[i].Columns[k].ColumnName + "':'" + ds.Tables[i].Rows[j][k].ToString() + "'";
                            json += string.Format("\"{0}\":\"{1}\",", ds.Tables[i].Columns[k].ColumnName, ds.Tables[i].Rows[j][k].ToString());
                            if (k != ds.Tables[i].Columns.Count - 1)
                                json += ",";
                        }
                        json += "}";
                        if (j < ds.Tables[i].Rows.Count - 1)
                            json += ",";
                    }
                    json += "]";
                    if (i != ds.Tables.Count - 1)
                        json += ",";


                }
                json += "}";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return json;
        }
        public static string ToJson(this DataRow dr)
        {
            string json = string.Empty;
            try
            {
                json = "{";

                
                for (int k = 0; k < dr.Table.Columns.Count; k++)
                {
                    //json +="'"+ ds.Tables[i].Columns[k].ColumnName + "':'" + ds.Tables[i].Rows[j][k].ToString() + "'";
                    json += string.Format("\"{0}\":\"{1}\"", dr.Table.Columns[k].ColumnName, StringToJSON( dr[dr.Table.Columns[k].ColumnName].ToString()));
                    if (k != dr.Table.Columns.Count - 1)
                        json += ",";
                }



                json += "}";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return json;
        }
        public static String StringToJSON(String tmp)
        {
            StringBuilder info = new StringBuilder();
            for (int i = 0; i < tmp.Length; i++)
            {
                char t = tmp[i];
                switch (t)
                {
                    case '\"':
                        info.Append("\\\"");
                        break;
                    case '\\':
                        info.Append("\\\\");
                        break;
                    case '/':
                        info.Append("\\/");
                        break;
                    case '\b':
                        info.Append("\\b");
                        break;
                    case '\f':
                        info.Append("\\f");
                        break;
                    case '\n':
                        info.Append("\\n");
                        break;
                    case '\r':
                        info.Append("\\r");
                        break;
                    case '\t':
                        info.Append("\\t");
                        break;
                    default:
                        info.Append(t);break;
                }
            }
            return info.ToString();
        }
        public static string ToJson(this DataTable dt)
        {
            string json = "{\"T1\":[";
            try
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    json += "{";
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        json += "\"" + dt.Columns[k].ColumnName + "\":\"" + StringToJSON(dt.Rows[j][k].ToString()) + "\"";
                        if (k != dt.Columns.Count - 1)
                            json += ",";
                    }
                    json += "}";
                    if (j < dt.Rows.Count - 1)
                        json += ",";
                }
                json += "]}";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return json;
        }
        public static string dsToJson(DataSet ds)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder("[");
            for (int o = 0; o < ds.Tables.Count; o++)
            {
                str.Append("{");
                str.Append(string.Format("\"{0}\":[", "mytest"));

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    str.Append("{");
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        str.Append(string.Format("\"{0}\":\"{1}\",", ds.Tables[0].Columns[j].ColumnName, ds.Tables[0].Rows[i][j].ToString()));
                    }
                    str.Remove(str.Length - 1, 1);
                    str.Append("},");
                }
                str.Remove(str.Length - 1, 1);
                str.Append("]},");
            }
            str.Remove(str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        /// <summary>
        /// json 不带T1
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToNewJson(this DataTable dt)
        {
            string json = "[";
            try
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    json += "{";
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        json += "\"" + dt.Columns[k].ColumnName + "\":\"" + dt.Rows[j][k].ToString() + "\"";
                        if (k != dt.Columns.Count - 1)
                            json += ",";
                    }
                    json += "}";
                    if (j < dt.Rows.Count - 1)
                        json += ",";
                }
                json += "]";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return json;
        }
    }
}
